package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.member;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivity;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityEnum;
import com.gzhryc.shared_device.oem.code.business.services.CouponActivityService;
import com.gzhryc.shared_device.oem.code.business.services.dto.CouponActivityPlaceSearch;
import com.gzhryc.shared_device.oem.code.business.services.dto.CouponActivitySearch;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberBusinessOrder;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.LoginUserSessionManager;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.member.MemberCouponListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.member.MemberCouponListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.member.MemberCouponSetRequest;

public class MemberCouponController {

    static Logger log = Logger.getLogger(MemberCouponController.class);

    /**
     * 获取订单可使用的优惠活动
     * @param request
     * @return
     */
    @Route(value = "/agent/api/v1/member/order/coupon_activity/list.data")
    public MemberCouponListResponse list(HttpServletRequest request) {
        MemberCouponListResponse apiResp = new MemberCouponListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        MemberCouponListRequest apiReq = WebUtils.getJsonRequest(request, MemberCouponListRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getCreateDate())){
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(),"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }

                MemberBusinessOrder order = MemberBusinessOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                if(order != null){
                    boolean isOverall = false;
                    Long userId = null;
                    if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                        isOverall = true;
                    }else {
                        PlaceProfitUser profitUser = PlaceProfitUserService.self().getByKeys(order.getPlaceId(),loginUser.getId());
                        if(profitUser != null){
                            if(ERoleType.Partner.index().equals(profitUser.getRoleType())) {
                                //合伙人，默认可以操作
                                isOverall = true;
                            }else if(ERoleType.Merchant.index().equals(profitUser.getRoleType())){
                                userId = profitUser.getPlaceUserId();
                            }
                        }else{
                            apiResp.setMsg("无权限查看");
                            return apiResp;
                        }
                    }

                    Integer pageNo = apiReq.getBody().getPageNo() == null ? 1 : apiReq.getBody().getPageNo();
                    if(isOverall){
                        //只限制业务类型 + 全不限制
                        CouponActivitySearch search1 = new CouponActivitySearch();
                        search1.setUserId(loginUser.getId());
                        search1.setType(CouponActivityEnum.Type.HandSend.index());
                        search1.setCouponType(apiReq.getBody().getCouponType());
                        search1.setBusinessType(order.getBusinessType());
                        search1.setUseRange(CouponActivityEnum.UseRange.Unlimited.index());
                        search1.setState(CouponActivityEnum.State.Enable.index());

                        CouponActivitySearch search2 = new CouponActivitySearch();
                        search2.setUserId(loginUser.getId());
                        search2.setType(CouponActivityEnum.Type.HandSend.index());
                        search2.setCouponType(apiReq.getBody().getCouponType());
                        search2.setUseLimit(CouponActivityEnum.UseLimit.Unlimited.index());
                        search2.setUseRange(CouponActivityEnum.UseRange.Unlimited.index());
                        search2.setState(CouponActivityEnum.State.Enable.index());

                        List<CouponActivity> couponActivityList = CouponActivityService.self().findBySearch(search1,search2,pageNo,WebConstants.PAGE_LIMIT);
                        if(couponActivityList != null && couponActivityList.size() > 0){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                            apiResp.getBody().setItems(new ArrayList<>());
                            for(CouponActivity couponActivity : couponActivityList){
                                MemberCouponListResponse.Item item = new MemberCouponListResponse.Item();
                                item.setActivityId(couponActivity.getId());
                                item.setTitle(couponActivity.getTitle());
                                item.setNote(couponActivity.getNote());
                                item.setCouponInfo(couponActivity.getCouponInfo());
                                item.setStartDate(couponActivity.getStartDate());
                                item.setEndDate(couponActivity.getEndDate());
                                apiResp.getBody().getItems().add(item);
                            }
                        }
                    }else if(userId != null){
                        //使用指定网点
                        CouponActivityPlaceSearch couponActivityPlaceSearch1 = new CouponActivityPlaceSearch();
                        couponActivityPlaceSearch1.setPlaceId(order.getPlaceId());
                        couponActivityPlaceSearch1.setCouponActivity(new CouponActivity());
                        couponActivityPlaceSearch1.getCouponActivity().setUserId(userId);
                        couponActivityPlaceSearch1.getCouponActivity().setBusinessType(order.getBusinessType());
                        couponActivityPlaceSearch1.setState(CouponActivityEnum.State.Enable.index());

                        CouponActivityPlaceSearch couponActivityPlaceSearch2 = new CouponActivityPlaceSearch();
                        couponActivityPlaceSearch2.setPlaceId(order.getPlaceId());
                        couponActivityPlaceSearch2.setCouponActivity(new CouponActivity());
                        couponActivityPlaceSearch2.getCouponActivity().setUserId(userId);
                        couponActivityPlaceSearch2.getCouponActivity().setUseLimit(CouponActivityEnum.UseLimit.Unlimited.index());
                        couponActivityPlaceSearch2.setState(CouponActivityEnum.State.Enable.index());
                    }
                }else{
                    apiResp.setMsg("未找到订单信息");
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/member/order/coupon_activity/set.do")
    public DefaultAPIResponse doSet(HttpServletRequest request){
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "发放失败，请联系客服");
        MemberCouponSetRequest apiReq = WebUtils.getJsonRequest(request, MemberCouponSetRequest.class);
        if (apiReq != null && apiReq.getBody().getCouponActivityId() != null && apiReq.getBody().getMemberId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                CouponActivity couponActivity = CouponActivityService.self().getJoinById(apiReq.getBody().getCouponActivityId());
                if (couponActivity != null && CouponActivityEnum.State.Enable.index().equals(couponActivity.getState())) {
                    Integer roleType = null;
                    if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                        if(!loginUser.getId().equals(couponActivity.getUserId())){
                            apiResp.setMsg("无权限操作");
                            return apiResp;
                        }
                    }else if(apiReq.getBody().getPlaceId() != null){
                        PlaceProfitUser profitUser = PlaceProfitUserService.self().getByKeys(apiReq.getBody().getPlaceId() ,loginUser.getId());
                        if(profitUser != null){
                            if(ERoleType.Partner.index().equals(loginUser.getRoleType())){
                                if(!profitUser.getUserId().equals(couponActivity.getUserId())) {
                                    apiResp.setMsg("无权限操作");
                                    return apiResp;
                                }
                            }else if(!ERoleType.Merchant.index().equals(loginUser.getRoleType())){
                                apiResp.setMsg("无权限操作");
                                return apiResp;
                            }
                            roleType = profitUser.getRoleType();
                        }else{
                            apiResp.setMsg("无权限操作");
                            return apiResp;
                        }
                    }else{
                        apiResp.setMsg("无权限操作");
                        return apiResp;
                    }

                    Member member = MemberService.self().getById(apiReq.getBody().getMemberId());
                    if(member == null){
                        apiResp.setMsg("未找到会员信息");
                        return apiResp;
                    }
                    OperateInfo operateInfo = LoginUserSessionManager.self().getOperateInfo(loginUser,roleType);
                    try {
                        if(CouponActivityService.self().memberReceive(couponActivity,member.getId(),member.getNickname()
                                ,apiReq.getBody().getPlaceId(),operateInfo)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,"发放成功");
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else{
                    apiResp.setMsg("优惠活动不存在或状态异常");
                }
            }
        }
        return apiResp;
    }
}
